package com.xyz.websocketclientdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

/**
 * @author Zhang Yu
 * @description: TODO
 * @date 2024/4/24 14:09
 */
@Configuration
@Slf4j
public class WebSocketConfig {

    @Bean
    public WebSocketClient webSocketClient() {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8080/websocket/7056"),new Draft_6455()) {

                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    log.info("[websocket] 连接成功");
                }


                @Override
                public void onMessage(String message) {
                    log.info("[websocket String] 收到消息={}",message);
                }

                @Override
                public void onMessage(ByteBuffer bytes) {
                    String str = ByteBuffer2String(bytes);
                    log.info("[websocket ByteBuffer] 收到消息={}",str);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("[websocket] 退出连接");
                }


                @Override
                public void onError(Exception ex) {
                    log.info("[websocket] 连接错误={}",ex.getMessage());
                }
                private String ByteBuffer2String(ByteBuffer buffer) {
                    Charset charset = Charset.forName("utf-8");
                    CharBuffer charBuffer = charset.decode(buffer);
                    String s = charBuffer.toString();
                    return s;
                }

            };

            webSocketClient.connect();
            return webSocketClient;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;
    }
}
